package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"text-mng-sys/model"
)

func TextAdd(c *gin.Context) {
	Title := c.PostForm("Title")
	Content := c.PostForm("Content")
	Author := c.PostForm("Author")
	data := model.Text{
		Title:   Title,
		Content: Content,
		Author:  Author,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func TextList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var text []model.Text
	err := model.DB.Debug().Offset(offset).Limit(size).Find(&text).Error
	var count int64
	model.DB.Model(&text).Count(&count)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  text,
		"count": count,
	})
	return
}

func TextDetail(c *gin.Context) {
	id := c.Query("id")
	var text model.Text
	err := model.DB.Debug().Where("id=?", id).First(&text).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": text,
	})
	return
}

func TextLike(c *gin.Context) {
	tid, _ := strconv.Atoi(c.PostForm("tid"))
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	data := model.TextLike{
		Tid: tid,
		Uid: uid,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "点赞成功",
	})
	return
}
